import React, { useState, useEffect } from 'react';
import { Calendar, Clock, FileText, Download, Play, Loader2, FolderOpen, Users, ChevronDown, BarChart3 } from 'lucide-react';
import { ProjectConfig, AppConfig } from '../types';
import { BrowserGitService, GitChange } from '../services/BrowserGitService';
import { EnhancedAIService } from '../services/EnhancedAIService';
import { LocalStorageService } from '../services/LocalStorageService';
import { ConfigService } from '../services/ConfigService';

interface ReportGeneratorProps {
  config: AppConfig;
  onMessage: (type: 'success' | 'error', text: string) => void;
}

type TimeRange = 'today' | 'week' | 'custom';
type ReportFormat = 'markdown' | 'text';
type ReportStyle = 'simple' | 'detailed';
type ReportType = 'daily' | 'weekly';

interface ReportResult {
  content: string;
  summary: string;
  generatedAt: string;
  timeRange: string;
  projectName: string;
  format: ReportFormat;
  style: ReportStyle;
  type: ReportType;
}

export const ReportGenerator: React.FC<ReportGeneratorProps> = ({ config, onMessage }) => {
  const [projects, setProjects] = useState<ProjectConfig[]>([]);
  const [selectedProject, setSelectedProject] = useState<ProjectConfig | null>(null);
  const [timeRange, setTimeRange] = useState<TimeRange>('today');
  const [customStartDate, setCustomStartDate] = useState('');
  const [customEndDate, setCustomEndDate] = useState('');
  const [authorFilter, setAuthorFilter] = useState('');
  const [availableAuthors, setAvailableAuthors] = useState<string[]>([]);
  const [generating, setGenerating] = useState(false);
  const [report, setReport] = useState<ReportResult | null>(null);
  const [showReport, setShowReport] = useState(false);
  const [reportFormat, setReportFormat] = useState<ReportFormat>('markdown');
  const [reportStyle, setReportStyle] = useState<ReportStyle>('simple');
  const [reportType, setReportType] = useState<ReportType>('daily');
  const [includeDiff, setIncludeDiff] = useState<boolean>(false);
  const [browserGitService] = useState(() => new BrowserGitService());
  const [configLoaded, setConfigLoaded] = useState(false);
  const [currentConfig, setCurrentConfig] = useState<AppConfig>({} as AppConfig);



  // 加载项目列表和设置默认日期
  useEffect(() => {
    const loadProjects = () => {
      const projectList = LocalStorageService.getProjects();
      setProjects(projectList);
      
      // 尝试加载上次选中的项目
      const lastSelected = LocalStorageService.getSelectedProject();
      if (lastSelected && projectList.find(p => p.id === lastSelected.id)) {
        setSelectedProject(lastSelected);
      }
    };
    
    loadProjects();
    
    // 设置默认日期
    const today = new Date();
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    if (!customStartDate) {
      setCustomStartDate(weekAgo.toISOString().split('T')[0]);
    }
    if (!customEndDate) {
      setCustomEndDate(today.toISOString().split('T')[0]);
    }
    
    // 如果配置中有Git用户名且当前没有设置作者筛选，自动设置
    if (config.gitUsername && !authorFilter) {
      setAuthorFilter(config.gitUsername);
    }
  }, [customStartDate, customEndDate, config.gitUsername, authorFilter]);

  // 监听配置变更，自动保存
  useEffect(() => {
    if (configLoaded && selectedProject) {
      // 延迟保存，避免频繁更新
      const timer = setTimeout(() => {
        saveConfigToFile();
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [reportFormat, reportStyle, authorFilter, configLoaded, selectedProject]);

  // 处理项目选择
  const handleProjectSelect = async (project: ProjectConfig) => {
    setSelectedProject(project);
    
    // 保存选中的项目
    LocalStorageService.setSelectedProject(project);
    
    try {
      // 设置项目路径到Git服务
      await browserGitService.setProjectPath(project.path);
      
      // 尝试加载项目配置文件
      await loadProjectConfig(project);
      
      // 检查是否已经选择了Git仓库
      if (browserGitService.hasSelectedRepository()) {
        onMessage('success', `已选择项目: ${project.name}，Git仓库已就绪`);
        await loadAvailableAuthors();
      } else {
        // 项目已配置但Git仓库未选择，提示用户选择
        onMessage('success', `已选择项目: ${project.name}`);
        onMessage('error', `请点击"手动选择Git仓库"来选择项目 ${project.name} 对应的Git仓库目录`);
      }
    } catch (err: any) {
      onMessage('error', `项目选择失败: ${err.message}`);
    }
  };

  // 加载项目配置文件
  const loadProjectConfig = async (project: ProjectConfig) => {
    try {
      // 在浏览器环境中，我们需要用户手动选择项目目录来访问配置文件
      // 这里我们先从localStorage加载基本配置，然后在用户选择目录时同步
      const config = await ConfigService.getConfig();
      setCurrentConfig(config);
      
      // 如果配置中有选中的项目ID，应用到当前设置
      if (config.selectedProjectId === project.id) {
        // 应用配置中的设置（使用默认值）
        setReportFormat('markdown');
        setReportStyle('simple');
        
        // 如果配置中有Git用户名，设置为作者筛选
        if (config.gitUsername) {
          setAuthorFilter(config.gitUsername);
        }
        setConfigLoaded(true);
        console.log('项目配置已加载:', config);
      }
    } catch (error) {
      console.warn('加载项目配置失败:', error);
    }
  };

  // 保存配置到文件
  const saveConfigToFile = async () => {
    try {
      const configToSave: Partial<AppConfig> = {
        selectedProjectId: selectedProject?.id,
        gitUsername: authorFilter || config.gitUsername,
        aiProvider: config.aiProvider
      };
      
      await ConfigService.saveConfig({ ...currentConfig, ...configToSave });
      setCurrentConfig({ ...currentConfig, ...configToSave });
      
      // 在实际项目中，这里会保存到文件
      // 由于浏览器限制，我们暂时只更新内存中的配置
      console.log('配置已更新:', configToSave);
    } catch (error) {
      console.error('保存配置失败:', error);
    }
  };

  // 加载可用的作者列表
  const loadAvailableAuthors = async () => {
    try {
      if (!browserGitService.hasSelectedRepository()) return;
      
      console.log('开始加载可用作者列表...');
      
      // 使用新的getAvailableAuthors方法获取最近30天的作者列表
      const authors = await browserGitService.getAvailableAuthors(30);
      
      console.log('加载到的作者列表:', authors);
      setAvailableAuthors(authors);
      
      // 如果配置中有Git用户名且在作者列表中，自动设置为筛选条件
      if (config.gitUsername && authors.includes(config.gitUsername) && !authorFilter) {
        setAuthorFilter(config.gitUsername);
        console.log(`自动设置作者筛选为: ${config.gitUsername}`);
      }
    } catch (err) {
      console.warn('无法加载作者列表:', err);
      setAvailableAuthors([]);
    }
  };

  const selectGitRepository = async () => {
    try {
      const result = await browserGitService.selectGitRepository();
      if (result.success) {
        // 创建一个临时项目对象来表示选中的Git仓库
        const repoName = result.data || 'Git仓库';
        const tempProject: ProjectConfig = {
          id: 'temp-git-repo',
          name: repoName,
          path: '', // 新架构下不需要路径
          addedAt: new Date().toISOString()
        };
        setSelectedProject(tempProject);
        onMessage('success', '已选择Git仓库，可以开始生成报告');
        
        // 获取可用的作者列表
        await loadAvailableAuthors();
      } else {
        onMessage('error', result.error || '选择Git仓库失败或用户取消');
      }
    } catch (error: any) {
      onMessage('error', `选择Git仓库失败: ${error.message}`);
    }
  };

  const generateReport = async () => {
    const currentApiKey = config.apiKeys[config.aiProvider];
    if (!currentApiKey && !hasEnvironmentApiKey()) {
      onMessage('error', `请先配置${config.aiProvider}的API密钥`);
      return;
    }

    // 检查是否已选择项目或Git仓库
    if (!selectedProject) {
      onMessage('error', '请先选择项目或Git仓库目录');
      return;
    }
    
    // 验证Git仓库是否已正确选择
    if (!browserGitService.hasSelectedRepository()) {
      // 如果没有选择Git仓库，提供更明确的指导
      if (browserGitService.hasConfiguredProject()) {
        onMessage('error', `项目 ${selectedProject.name} 已配置，但需要手动选择对应的Git仓库目录才能生成报告`);
      } else {
        onMessage('error', '请先选择项目并手动选择Git仓库目录');
      }
      return;
    }

    try {
      setGenerating(true);
      setReport(null);
      setShowReport(false);

      // 计算时间范围
      let startDate: string;
      let endDate: string;
      let rangeText: string;

      const today = new Date();
      const todayStr = today.toISOString().split('T')[0];

      switch (timeRange) {
        case 'today':
          startDate = todayStr;
          endDate = todayStr;
          rangeText = '今日';
          break;
        case 'week':
          const dayOfWeek = today.getDay(); // 0=周日, 1=周一, ..., 6=周六
          // 计算本周一的日期 - 如果是周日，往前推6天到周一；否则计算到周一的偏移
          const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
          const startOfWeek = new Date(today.getTime() + mondayOffset * 24 * 60 * 60 * 1000);
          // 计算本周日的日期 - 周报应该包含完整的一周数据（周一到周日）
          const sundayOffset = dayOfWeek === 0 ? 0 : 7 - dayOfWeek;
          const endOfWeek = new Date(today.getTime() + sundayOffset * 24 * 60 * 60 * 1000);
          startDate = startOfWeek.toISOString().split('T')[0];
          endDate = endOfWeek.toISOString().split('T')[0];
          rangeText = '本周';
          break;
        case 'custom':
          startDate = customStartDate;
          endDate = customEndDate;
          rangeText = `${startDate} 至 ${endDate}`;
          break;
        default:
          throw new Error('无效的时间范围');
      }

      // 浏览器环境 - 使用本地Git文件分析
      onMessage('success', '正在分析Git仓库...');
      
      console.log('开始分析Git变更，参数:', {
        startDate,
        endDate,
        authorFilter,
        excludePatterns: config.excludePatterns || []
      });
      
      // 分析Git变更（包含作者筛选）
      const filteredChanges = await browserGitService.analyzeChanges(
        startDate,
        endDate,
        config.excludePatterns || [],
        authorFilter, // 直接传递作者筛选参数
        includeDiff // 传递includeDiff参数
      );

        if (filteredChanges.length === 0) {
          const message = authorFilter 
            ? `在指定时间范围内未找到作者"${authorFilter}"的代码变更`
            : '在指定时间范围内未找到代码变更';
          onMessage('error', message);
          const reportResult: ReportResult = {
            content: message + '，请检查时间范围设置或作者筛选条件。',
            summary: '未找到代码变更',
            generatedAt: new Date().toLocaleString('zh-CN'),
            timeRange: rangeText,
            projectName: selectedProject?.name || 'Git仓库',
            format: reportFormat,
            style: reportStyle,
            type: reportType
          };
          setReport(reportResult);
          setShowReport(true);
          return;
        }

        onMessage('success', '正在生成AI报告...');
        
        // 生成AI报告
        const aiService = new EnhancedAIService();
        const reportResult = await aiService.generateWorkReport(
          filteredChanges, 
          reportType, // 使用选择的报告类型
          startDate, 
          endDate, 
          config.aiProvider, 
          currentApiKey || '',
          {
            format: reportFormat,
            style: reportStyle,
            includeCodeDetails: includeDiff || reportStyle === 'detailed'
          }
        );

        if (reportResult.success && reportResult.data) {
          const finalReport: ReportResult = {
            content: reportResult.data,
            summary: authorFilter 
              ? `分析了作者"${authorFilter}"的 ${filteredChanges.length} 个文件变更`
              : `分析了 ${filteredChanges.length} 个文件变更`,
            generatedAt: new Date().toLocaleString('zh-CN'),
            timeRange: rangeText,
            projectName: selectedProject?.name || 'Git仓库',
            format: reportFormat,
            style: reportStyle,
            type: reportType
          };
          setReport(finalReport);
          setShowReport(true);
          onMessage('success', `报告生成成功！分析了 ${filteredChanges.length} 个文件变更`);
        } else {
          onMessage('error', reportResult.error || 'AI报告生成失败');
        }
    } catch (error) {
      onMessage('error', `报告生成失败: ${error}`);
    } finally {
      setGenerating(false);
    }
  };

  const exportReport = async () => {
    if (!report) return;

    try {
      // 根据格式选择MIME类型和文件扩展名
      const mimeType = report.format === 'markdown' ? 'text/markdown;charset=utf-8' : 'text/plain;charset=utf-8';
      const fileExtension = report.format === 'markdown' ? 'md' : 'txt';
      const styleText = report.style === 'simple' ? '简洁版' : '详细版';
      const typeText = report.type === 'daily' ? '日报' : '周报';
      
      // 浏览器环境，下载文件
      const blob = new Blob([report.content], { type: mimeType });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${report.projectName}_${typeText}_${styleText}_${report.timeRange}_${new Date().toISOString().split('T')[0]}.${fileExtension}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      onMessage('success', `${report.format === 'markdown' ? 'Markdown' : '纯文本'}格式报告已下载到本地！`);
    } catch (error) {
      onMessage('error', `导出失败: ${error}`);
    }
  };

  const hasEnvironmentApiKey = () => {
    // 在浏览器环境中，无法直接检测环境变量
    // 这里返回false，用户需要手动输入API密钥
    return false;
  };



  return (
    <div className="space-y-6">
      {/* 报告生成控制面板 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-center mb-6">
          <FileText className="h-6 w-6 text-blue-600 mr-2" />
          <h2 className="text-xl font-semibold text-gray-900">生成工作报告</h2>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
          {/* 项目选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              选择项目
            </label>
            <div className="space-y-3">
              {/* 项目列表 */}
              {projects.length > 0 && (
                <div className="space-y-2">
                  <select
                    value={selectedProject?.id || ''}
                    onChange={(e) => {
                      const project = projects.find(p => p.id === e.target.value);
                      if (project) handleProjectSelect(project);
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="">请选择项目...</option>
                    {projects.map(project => (
                      <option key={project.id} value={project.id}>
                        {project.name}
                      </option>
                    ))}
                  </select>
                </div>
              )}
              
              {/* 手动选择Git仓库 */}
              <button
                onClick={selectGitRepository}
                className="w-full flex items-center justify-center px-4 py-3 border-2 border-neutral-300 rounded-xl hover:bg-neutral-50 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all duration-300 font-medium shadow-soft hover:shadow-medium"
              >
                <FolderOpen className="h-5 w-5 mr-3" />
                <span>{projects.length > 0 ? '或手动选择Git仓库' : '选择Git仓库目录'}</span>
              </button>
              
              {/* 当前选中项目显示 */}
              {selectedProject && (
                <div className={`p-3 border rounded-md ${
                  browserGitService.hasSelectedRepository() 
                    ? 'bg-green-50 border-green-200' 
                    : 'bg-yellow-50 border-yellow-200'
                }`}>
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <div className={`w-2 h-2 rounded-full ${
                        browserGitService.hasSelectedRepository() 
                          ? 'bg-green-500' 
                          : 'bg-yellow-500'
                      }`}></div>
                    </div>
                    <div className="ml-3 flex-1">
                      <p className={`text-sm font-medium ${
                        browserGitService.hasSelectedRepository() 
                          ? 'text-green-800' 
                          : 'text-yellow-800'
                      }`}>
                        当前项目: {selectedProject.name}
                      </p>
                      <p className={`text-xs ${
                        browserGitService.hasSelectedRepository() 
                          ? 'text-green-600' 
                          : 'text-yellow-600'
                      }`}>
                        {browserGitService.hasSelectedRepository() 
                          ? '✓ Git仓库已就绪，可以生成报告' 
                          : '⚠ 需要手动选择Git仓库目录'
                        }
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 作者筛选 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Users className="h-4 w-4 inline mr-1" />
              按作者筛选（可选）
            </label>
            <div className="space-y-3">
              {/* 作者输入框 */}
              <input
                type="text"
                value={authorFilter}
                onChange={(e) => setAuthorFilter(e.target.value)}
                placeholder={config.gitUsername ? `默认: ${config.gitUsername}` : "输入作者姓名进行筛选..."}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
              
              {/* 系统配置的Git用户名提示 */}
              {config.gitUsername && (
                <div className="flex items-center justify-between text-xs">
                  <span className="text-gray-500">
                    系统配置用户: {config.gitUsername}
                  </span>
                  {authorFilter !== config.gitUsername && (
                    <button
                      onClick={() => setAuthorFilter(config.gitUsername)}
                      className="text-primary-600 hover:text-primary-800 font-medium transition-colors duration-200"
                    >
                      使用系统配置
                    </button>
                  )}
                </div>
              )}
              
              {/* 可用作者列表 */}
              {availableAuthors.length > 0 && (
                <div className="space-y-1">
                  <p className="text-xs text-gray-500">最近的作者:</p>
                  <div className="flex flex-wrap gap-1">
                    {availableAuthors.slice(0, 5).map(author => (
                      <button
                        key={author}
                        onClick={() => setAuthorFilter(author)}
                        className={`px-3 py-2 text-sm rounded-xl border-2 transition-all duration-300 font-medium shadow-soft hover:shadow-medium ${
                          author === config.gitUsername 
                            ? 'bg-primary-100 hover:bg-primary-200 text-primary-700 border-primary-300' 
                            : 'bg-neutral-100 hover:bg-neutral-200 text-neutral-700 border-neutral-300'
                        }`}
                      >
                        {author}
                        {author === config.gitUsername && ' (系统配置)'}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              
              {/* 清除筛选 */}
              {authorFilter && (
                <button
                  onClick={() => setAuthorFilter('')}
                  className="text-sm text-primary-600 hover:text-primary-800 font-medium transition-colors duration-200"
                >
                  清除作者筛选
                </button>
              )}
            </div>
          </div>

          {/* 报告配置 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              报告配置
            </label>
            <div className="space-y-4">
              {/* 报告类型 */}
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">报告类型</label>
                <div className="flex space-x-3">
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="daily"
                      checked={reportType === 'daily'}
                      onChange={(e) => setReportType(e.target.value as ReportType)}
                      className="mr-1"
                    />
                    <span className="text-sm">日报</span>
                  </label>
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="weekly"
                      checked={reportType === 'weekly'}
                      onChange={(e) => setReportType(e.target.value as ReportType)}
                      className="mr-1"
                    />
                    <span className="text-sm">周报</span>
                  </label>
                </div>
              </div>
              
              {/* 报告格式 */}
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">输出格式</label>
                <div className="flex space-x-3">
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="markdown"
                      checked={reportFormat === 'markdown'}
                      onChange={(e) => setReportFormat(e.target.value as ReportFormat)}
                      className="mr-1"
                    />
                    <span className="text-sm">Markdown</span>
                  </label>
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="text"
                      checked={reportFormat === 'text'}
                      onChange={(e) => setReportFormat(e.target.value as ReportFormat)}
                      className="mr-1"
                    />
                    <span className="text-sm">纯文本</span>
                  </label>
                </div>
              </div>
              
              {/* 报告风格 */}
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">语义风格</label>
                <div className="flex space-x-3">
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="simple"
                      checked={reportStyle === 'simple'}
                      onChange={(e) => setReportStyle(e.target.value as ReportStyle)}
                      className="mr-1"
                    />
                    <span className="text-sm">简单明了</span>
                  </label>
                  <label className="flex items-center">
                    <input
                      type="radio"
                      value="detailed"
                      checked={reportStyle === 'detailed'}
                      onChange={(e) => setReportStyle(e.target.value as ReportStyle)}
                      className="mr-1"
                    />
                    <span className="text-sm">详细专业</span>
                  </label>
                </div>
              </div>
              
              {/* 代码差异选项 */}
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">代码内容</label>
                <div className="flex items-center space-x-2">
                  <label className="flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={includeDiff}
                      onChange={(e) => setIncludeDiff(e.target.checked)}
                      className="mr-2 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <span className="text-sm text-gray-700">包含代码差异</span>
                  </label>
                </div>
                <p className="text-xs text-gray-500 mt-1">
                  开启后将在报告中包含具体的代码变更内容，生成更详细的分析报告
                </p>
              </div>
            </div>
          </div>

          {/* 时间范围选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              时间范围
            </label>
            <div className="space-y-2">
              <div className="flex space-x-4">
                <label className="flex items-center">
                  <input
                    type="radio"
                    value="today"
                    checked={timeRange === 'today'}
                    onChange={(e) => setTimeRange(e.target.value as TimeRange)}
                    className="mr-2"
                  />
                  <Clock className="h-4 w-4 mr-1" />
                  今日
                </label>
                <label className="flex items-center">
                  <input
                    type="radio"
                    value="week"
                    checked={timeRange === 'week'}
                    onChange={(e) => setTimeRange(e.target.value as TimeRange)}
                    className="mr-2"
                  />
                  <Calendar className="h-4 w-4 mr-1" />
                  本周
                </label>
                <label className="flex items-center">
                  <input
                    type="radio"
                    value="custom"
                    checked={timeRange === 'custom'}
                    onChange={(e) => setTimeRange(e.target.value as TimeRange)}
                    className="mr-2"
                  />
                  自定义
                </label>
              </div>

              {/* 自定义日期范围 */}
              {timeRange === 'custom' && (
                <div className="flex space-x-2 mt-2">
                  <input
                    type="date"
                    value={customStartDate}
                    onChange={(e) => setCustomStartDate(e.target.value)}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                  <span className="flex items-center text-gray-500">至</span>
                  <input
                    type="date"
                    value={customEndDate}
                    onChange={(e) => setCustomEndDate(e.target.value)}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 生成按钮 */}
        <div className="mt-8 flex justify-center">
          <button
            onClick={generateReport}
            disabled={generating || !selectedProject || !browserGitService.hasSelectedRepository()}
            className="flex items-center px-8 py-4 bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-2xl hover:from-primary-700 hover:to-primary-800 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 font-bold text-lg shadow-strong hover:shadow-stronger transform hover:scale-105"
          >
            {generating ? (
              <>
                <Loader2 className="h-6 w-6 mr-3 animate-spin" />
                <span>生成中...</span>
              </>
            ) : (
              <>
                <Play className="h-6 w-6 mr-3" />
                <span>生成报告</span>
              </>
            )}
          </button>
        </div>
      </div>

      {/* 报告显示区域 */}
      {showReport && report && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="text-xl font-bold text-gray-900">
                {report.projectName} - {report.type === 'daily' ? '日报' : '周报'} ({report.timeRange})
              </h3>
              <div className="flex flex-wrap items-center gap-4 mt-2 text-sm text-gray-500">
                <span>生成时间: {report.generatedAt}</span>
                <span className="flex items-center">
                  <span className={`inline-block w-2 h-2 rounded-full mr-1 ${
                    report.format === 'markdown' ? 'bg-blue-500' : 'bg-green-500'
                  }`}></span>
                  {report.format === 'markdown' ? 'Markdown格式' : '纯文本格式'}
                </span>
                <span className={`px-2 py-1 rounded text-xs ${
                  report.style === 'simple' 
                    ? 'bg-blue-100 text-blue-700' 
                    : 'bg-purple-100 text-purple-700'
                }`}>
                  {report.style === 'simple' ? '简单明了' : '详细专业'}
                </span>
              </div>
              {authorFilter && (
                <p className="text-sm text-blue-600 mt-2">
                  <Users className="h-4 w-4 inline mr-1" />
                  筛选作者: {authorFilter}
                </p>
              )}
            </div>
            <div className="flex space-x-4">
              <button
                onClick={() => {
                  // 复制报告内容到剪贴板
                  navigator.clipboard.writeText(report.content).then(() => {
                    onMessage('success', '报告内容已复制到剪贴板！');
                  }).catch(() => {
                    onMessage('error', '复制失败，请手动复制');
                  });
                }}
                className="flex items-center px-4 py-3 bg-gradient-to-r from-neutral-600 to-neutral-700 text-white rounded-xl hover:from-neutral-700 hover:to-neutral-800 transition-all duration-300 font-medium shadow-medium hover:shadow-strong transform hover:scale-105"
              >
                <FileText className="h-5 w-5 mr-2" />
                <span>复制</span>
              </button>
              <button
                onClick={exportReport}
                className="flex items-center px-4 py-3 bg-gradient-to-r from-success-600 to-success-700 text-white rounded-xl hover:from-success-700 hover:to-success-800 transition-all duration-300 font-medium shadow-medium hover:shadow-strong transform hover:scale-105"
              >
                <Download className="h-5 w-5 mr-2" />
                <span>导出报告</span>
              </button>
            </div>
          </div>

          {/* 报告摘要和统计 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
            {/* 报告摘要 */}
            <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
              <h4 className="font-semibold text-blue-900 mb-2 flex items-center">
                <FileText className="h-4 w-4 mr-2" />
                报告摘要
              </h4>
              <p className="text-blue-800 text-sm">{report.summary}</p>
            </div>
            
            {/* 快速统计 */}
            <div className="p-4 bg-green-50 rounded-lg border border-green-200">
              <h4 className="font-semibold text-green-900 mb-2 flex items-center">
                <BarChart3 className="h-4 w-4 mr-2" />
                快速统计
              </h4>
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="text-green-800">
                  <span className="font-medium">报告长度:</span> {Math.round(report.content.length / 100) / 10}K字符
                </div>
                <div className="text-green-800">
                  <span className="font-medium">报告类型:</span> {report.type === 'daily' ? '日报' : '周报'}
                </div>
                <div className="text-green-800">
                  <span className="font-medium">输出格式:</span> {report.format === 'markdown' ? 'Markdown' : '纯文本'}
                </div>
                <div className="text-green-800">
                  <span className="font-medium">语义风格:</span> {report.style === 'simple' ? '简单明了' : '详细专业'}
                </div>
                <div className="text-green-800">
                  <span className="font-medium">分析时间:</span> {report.timeRange}
                </div>
              </div>
            </div>
          </div>

          {/* 报告内容 */}
          <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-lg font-semibold text-gray-900">详细报告内容</h4>
                <div className="flex items-center space-x-2 text-sm text-gray-500">
                  <span>{report.format === 'markdown' ? 'Markdown格式' : '纯文本格式'}</span>
                  <span className="text-gray-300">|</span>
                  <span>{report.style === 'simple' ? '简洁风格' : '详细风格'}</span>
                </div>
              </div>
            
            {/* 格式化的报告内容 */}
            <div className="bg-gray-50 rounded-lg border overflow-hidden">
              <div className="bg-gray-100 px-4 py-2 border-b border-gray-200">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-gray-700">
                    {report.type === 'daily' ? '日报' : '周报'}内容 - {report.style === 'simple' ? '简洁版' : '详细版'}
                  </span>
                  <span className="text-xs text-gray-500">{report.format === 'markdown' ? 'Markdown格式' : '纯文本格式'}</span>
                </div>
              </div>
              <div className="p-6 max-h-96 overflow-y-auto">
                <div className="prose prose-sm max-w-none">
                  <pre className="whitespace-pre-wrap text-sm text-gray-800 leading-relaxed font-mono bg-white p-4 rounded border">
                    {report.content}
                  </pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};